<template>
    <div class="qilin-login">
        <div class="qilin-login-header">EDGQilin全栈管理系统-Vue2.x版</div>
        <div class="qilin-login-box">
            <template v-if="isLogin">
                <QilinForm :formConfig.sync="loginFormConfig" ref="formLogin"
                    @keyup.enter.native="login('formLogin')" key="formLogin"
                >
                    <!-- <template v-slot:isRemember="slotData">
                        <el-checkbox v-model="loginFormConfig.submitData.isRemember"
                            @click.native="slotData.onFocus"
                        >记住密码</el-checkbox>
                    </template> -->
                    <div class="qilin-login-box-tip" slot="form-login-tip">
                        还没有账号？现在<span @click="toRegister()">注册</span>|
                        <span @click="forgetPassword()">忘记密码？</span>
                    </div>
                </QilinForm>
            </template>
            <template v-else>
                <QilinForm :formConfig.sync="registerFormConfig" ref="formRegister"
                    @keyup.enter.native="register('formRegister')" key="formRegister"
                ></QilinForm>
            </template>
        </div>
    </div>
</template>
<script>
// @click与@keyup.enter.native不能存放在同一元素上同时使用
import jwt_decode from "jwt-decode";

import {setCookie,getCookie,clearCookie} from "@/utils/remember.js";
import {login,register} from "@/api/register/index.js";

export default {
    name:"login",
    data(){
        let validateConfirmPassword=(rule,value,callback)=>{
            if(!value){
                callback("确认密码不可为空");
            }else{
                if(value === this.$refs[rule.custom].ownFormConfig.submitData.password){
                    callback();
                }else{
                    callback("密码不一致");
                };
            };
        };
        return{
            isLogin:true,//当前是否显示登录表单页
            loginFormConfig:{// 登陆表单配置项
                itemConfig:[
                    {
                        dataName:"email", //绑定数据名
                        labelName:"邮箱", //表单label名
                        type:"input", //表单类型--输入框
                        inputType:"text", //输入框类型--文本输入（不写默认为text）
                        width:24, //宽度--可取值（6/8/12/16/18/24）
                        validate:[
                            // {
                            //     type:"email",
                            //     required:true,
                            //     message:"邮箱格式不正确",
                            //     // trigger:["blur","change"]
                            //     trigger:["blur"]
                            // }
                            {
                                required:true,
                                message:"请输入邮箱",
                                trigger:"blur"
                            }
                        ],
                        otherValidate:"emailValidator"
                    },
                    {
                        dataName:"password",
                        labelName:"密码",
                        type:"input",
                        inputType:"password", //输入框类型--密码输入框
                        showPassword:true, //是否显示输入密码--默认为false
                        width:24,
                        validate:[
                            {
                                required:true,
                                message:"请输入密码",
                                trigger:"blur"
                            }
                        ]
                    },
                    // {
                    //     dataName:"isRemember",
                    //     hideLabel:true,
                    //     type:"slot",
                    //     slotName:"isRemember",
                    //     width:24,
                    //     className:"qilin-item-isRemember"
                    // }
                    {
                        dataName:"isRemember",
                        hideLabel:true,
                        type:"checkbox",
                        dataListName:"isRemember",
                        width:24,
                        className:"qilin-item-isRemember"
                    }
                ],
                selectLists:{
                    isRemember:[
                        {
                            label:"记住密码"
                        }
                    ]
                },
                submitData:{
                    email:"",
                    password:"",
                    isRemember:false
                },
                buttonConfig:[
                    {
                        btnName:"登录", //按钮名称--默认为按钮
                        type:"primary", //按钮类型--默认为primary
                        className:"qilin-button", //按钮元素上的类名
                        formRefName:"formLogin", //当前组件元素的ref名称
                        click:this.login //按钮点击事件
                    }
                ]
            },
            registerFormConfig:{// 注册表单配置项
                elFormConfig:{
                    labelWidth:"80px"
                },
                itemConfig:[
                    {
                        dataName:"name",
                        labelName:"用户名",
                        type:"input",
                        inputType:"text",
                        width:24,
                        validate:[
                            {
                                required:true,
                                message:"请输入用户名",
                                trigger:"blur"
                            },
                            {
                                min:4,
                                max:12,
                                message:"用户名长度在4~12个字符之间",
                                trigger:"blur"
                            }
                        ]
                    },
                    {
                        dataName:"email",
                        labelName:"邮箱",
                        type:"input",
                        inputType:"text",
                        width:24,
                        validate:[
                            {
                                type:"email",
                                required:true,
                                message:"邮箱格式不正确",
                                trigger:["blur","change"]
                            }
                        ]
                    },
                    {
                        dataName:"password",
                        labelName:"密码",
                        type:"input",
                        inputType:"password",
                        width:24,
                        validate:[
                            {
                                required:true,
                                message:"请输入密码",
                                trigger:"blur"
                            }
                        ]
                    },
                    {
                        dataName:"confirmPassword",
                        labelName:"确认密码",
                        type:"input",
                        inputType:"password",
                        width:24,
                        validate:[
                            {
                                required:true,
                                trigger:"blur",
                                custom:"formRegister", //custom为自定义属性，用以当不同表单使用同一个校验方法时区分
                                validator:validateConfirmPassword
                            }
                        ]
                    },
                    // {
                    //     dataName:"identify",
                    //     labelName:"选择身份",
                    //     type:"select",
                    //     dataListName:"identifyList",
                    //     width:24
                    // }
                ],
                selectLists:{
                    identifyList:[
                        {
                            label:"管理员",
                            value:"manager"
                        },
                        {
                            label:"普通用户",
                            value:"employee"
                        }
                    ]
                },
                submitData:{
                    name:"",//用户名
                    email:"",//邮箱
                    password:"",//密码
                    confirmPassword:"",//确认密码
                    identify:"",//选择身份
                },
                buttonConfig:[
                    {
                        btnName:"注册",
                        type:"primary",
                        className:"qilin-button",
                        formRefName:"formRegister",
                        click:this.register
                    },
                    {
                        btnName:"返回登录",
                        type:"default",
                        click:()=>{this.isLogin=true;}
                    }
                ]
            }
        };
    },
    methods:{
        // 点击忘记密码事件监听
        forgetPassword(){
            this.$message({
                message:"请联系管理员方可修改密码!",
                type:"info"
            });
        },
        //点击注册文字事件监听
        toRegister(){
            this.isLogin=false;
        },
        //点击注册按钮事件监听
        register(refName){
            this.$refs[refName].formValidate((valid)=>{
                if(valid){
                    let params={
                        name:this.registerFormConfig.submitData.name,
                        email:this.registerFormConfig.submitData.email,
                        password:this.registerFormConfig.submitData.password,
                        identify:this.registerFormConfig.submitData.identify
                    };
                    register(params).then((res)=>{
                        // console.log(res);
                        if(res.code===1000){
                            this.$message({
                                message:"注册用户成功，请登录!",
                                type:"success"
                            });
                            this.isLogin=true;
                        }else{
                            this.$message({
                                message:res.message || "请求出错",
                                type:"error"
                            });
                        };
                    });
                };
            });
        },
        //点击登录按钮事件监听
        login(refName){
            this.$refs[refName].formValidate((valid)=>{
                if(valid){
                    let params={
                        email:this.loginFormConfig.submitData.email,
                        password:this.loginFormConfig.submitData.password
                    };
                    login(params).then((res)=>{
                        if(res.code===1000){
                            if(this.loginFormConfig.submitData.isRemember){
                                setCookie(this.loginFormConfig.submitData.email,this.loginFormConfig.submitData.password,15);
                            }else{
                                clearCookie();
                            };
                            this.$message({
                                message:`欢迎尊敬的${res.data.userInfo.name}用户登录EDGQiLin全栈管理系统！`,
                                type:"success"
                            });
                            if(res.data.userInfo.avatar.includes("//www")){
                                this.$Qilin.Storage.setKeyValueLocalStorage("avatar","moren");
                            }else{
                                this.$Qilin.Storage.setKeyValueLocalStorage("avatar",res.data.userInfo.avatar);
                            };
                            this.$Qilin.Storage.setKeyValueLocalStorage("email",res.data.userInfo.email);
                            localStorage.setItem("qilinToken",res.data.token);
                            const userInfo=jwt_decode(res.data.token); //解析token，获取token中的信息
                            this.$store.dispatch("setAuthenticated",!this.isEmpty(userInfo));
                            this.$store.dispatch("setUserInfo",{...userInfo,image:this.$Qilin.Storage.getValueLocalStorage("avatar")});
                            this.$router.push("/index");
                        }else{
                            this.$message({
                                message:res.message || "请求出错",
                                type:"error"
                            });
                        };
                    });
                };
            });
        },
        //判断是否为空的通用方法--若为空，则返回true
        isEmpty(value){
            return value === undefined || value === null ||
                (typeof value === "object" && Object.keys(value).length === 0) ||
                (typeof value === "string" && value.trim().length === 0);
        }
    },
    created(){
        let info=getCookie(this);
        if(info){
            if(info.username && info.username?.length > 0){
                this.loginFormConfig.submitData.email=info.username;
                this.loginFormConfig.submitData.password=info.password;
                this.loginFormConfig.submitData.isRemember=true;
            };
        };
    }
}
</script>
<style lang="less">
.qilin-login{
    width:420px;
    transform:translate(-50%,-50%);
    .EDGQilinPosition(absolute,40%,50%);
    >.qilin-login-header{
        width:100%;
        color:#fff;
        font-size:24px;
        font-weight:bolder;
        text-align:center;
        letter-spacing:1px;
        padding:20px;
    }
    >.qilin-login-box{
        background-color:#fff;
        border-radius:5px;
        padding:20px;
        .el-form{
            padding:20px 20px 0 20px;
            .qilin-button{
                width:50%;
            }
            .qilin-item-isRemember{
                text-align:right;
            }
        }
        .qilin-login-box-tip{
            font-size:12px;
            padding:0 20px 0 20px;
            text-align:right;
            color:@color-text-invalid;
            >span:first-child{
                color:#0094ff;
                cursor:pointer;
                font-weight:bolder;
                text-decoration:underline;
                margin-right:10px;
            }
            >span:last-of-type{
                margin-left:5px;
                color:#0094ff;
                cursor:pointer;
                font-weight:bolder;
            }
        }
    }
}
</style>